<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button
            type="primary"
            @click="addRoleVisible = true"
            class="addRoleBtn"
            >添加角色</el-button
          >
        </el-col>
      </el-row>

      <!-- 表格组件，表格数据从data中获取，每列数据从prop中获取 -->
      <el-table :data="roleList" style="width: 100%" border stripe>
        <!-- 添加展开项 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom', index1 === 0 ? 'bdtop' : '', 'vcenter']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  type="primary"
                  closable
                  @close="removeRights(scope.row, item1.id)"
                >
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限的容器 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                  :class="[index2 === 0 ? '' : 'bdtop', 'vcenter']"
                >
                  <!-- 渲染二级级权限 -->
                  <el-col :span="5">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRights(scope.row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限的容器 -->
                  <el-col :span="19">
                    <!-- 渲染三级级权限 -->
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRights(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 添加索引 -->
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="showEditDialog(scope.row.id)"
              icon="el-icon-edit"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDeleteRole(scope.row.id, scope.row.roleName)"
              icon="el-icon-delete"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              @click="showSetRightsDialog(scope.row)"
              icon="el-icon-setting"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色的对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleVisible"
      width="50%"
      @close="$refs.addRoleFormRef.resetFields()"
    >
      <el-form
        :model="addRoleForm"
        :rules="roleFormRules"
        ref="addRoleFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRoleVisible"
      width="50%"
      @close="$refs.editRoleFormRef.resetFields()"
    >
      <el-form
        :model="editRoleForm"
        :rules="roleFormRules"
        ref="editRoleFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightsVisible" width="50%">
      <!-- 树形控件 -->
      <el-tree
        :data="rightsList"
        :props="defaultTreeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defaultKeys"
        ref="treeRef"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      roleList: [],
      rightsList: [],
      addRoleForm: {
        roleName: '',
        roleDesc: '',
      },
      editRoleForm: {},
      //   控制对话框的显示与隐藏
      addRoleVisible: false,
      editRoleVisible: false,
      setRightsVisible: false,
      // 输入框规则
      roleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
        ],
      },
      // 默认的选中的节点id值
      defaultKeys: [],
      // 树形结构的默认设置
      defaultTreeProps: {
        children: 'children',
        label: 'authName',
      },
      // 角色id
      roleId: ''
    }
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200)
        return this.$message.error('获取角色列表失败')
      this.roleList = res.data
    },
    addRole() {
      // 先对表单进行预校验
      this.$refs.addRoleFormRef.validate(async (vaild) => {
        if (!vaild) return
        // 调用接口api，添加角色
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        if (res.meta.status !== 201) return this.$message.error('添加角色失败')
        // 关闭对话框
        this.addRoleVisible = false
        this.$message.success('添加角色成功')
        // 刷新表格
        this.getRoleList()
      })
    },
    async showEditDialog(id) {
      const { data: res } = await this.$http.get(`roles/${id}`)
      if (res.meta.status !== 200) return this.$message.error('查询信息失败')
      this.editRoleForm = res.data
      this.editRoleVisible = true
    },
    editRole() {
      this.$refs.editRoleFormRef.validate(async (vaild) => {
        if (!vaild) return
        const { data: res } = await this.$http.put(
          `roles/${this.editRoleForm.roleId}`,
          {
            roleName: this.editRoleForm.roleName,
            roleDesc: this.editRoleForm.roleDesc,
          }
        )
        if (res.meta.status !== 200)
          return this.$message.error('修改角色信息失败')
        // 关闭对话框
        this.editRoleVisible = false
        this.$message.success('修改角色信息成功')
        // 刷新表格
        this.getRoleList()
      })
    },
    async handleDeleteRole(id, roleName) {
      const confirmResult = await this.$confirm(
        `此操作将永久删除该角色 ${roleName}, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
      const { data: ref } = await this.$http.delete('roles/' + id)
      if (ref.meta.status !== 200) return this.$message.error(`角色 ${roleName} 删除失败!`)
      this.$message.success(`角色 ${roleName} 删除成功!`)
      this.getRoleList()
    },
    async removeRights(role, rightsId) {
      // 之所以传role，是因为最后需要更新role.children,使页面做局部刷新
      const confirmResult = await this.$confirm(
        `此操作将永久删除该权限, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
      const { data: ref } = await this.$http.delete(
        `roles/${role.id}/rights/${rightsId}`
      )
      if (ref.meta.status !== 200) return
      role.children = ref.data
      this.$message.success(`权限删除成功!`)
      //   this.getRoleList()
    },
    async showSetRightsDialog(role) {
      // 将角色id保存到roleId中，给分配权限时，提供便利
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200)
        return this.$message.error('获取权限列表失败')
      this.rightsList = res.data
      // 在获取三级节点前，先清空其他角色上一次获取到三级节点id。或者在对话框添加@close事件，就这句话作为事件执行体也是一样的
      this.defaultKeys = []
      // 递归获取三级节点id
      this.getLeafKeys(role, this.defaultKeys)
      this.setRightsVisible = true
    },
    // 通过递归的形式，获取角色下所有的三级权限的id，并保存到defaultKeys数组中
    getLeafKeys(node, arr) {
      // 先判断是否为三级节点，包含children属性就不是三级节点
      if(!node.children){
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      });
    },
    // 点击为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      // 发送网络请求
      const {data: ref} = await this.$http.post(`roles/${this.roleId}/rights`, {rids: idStr})
      if(ref.meta.status !== 200) {
        return this.$message.error('更新权限失败')
      }
      this.$message.success('更新权限成功')
      this.getRoleList()
      this.setRightsVisible = false
    },
  },
  created() {
    this.getRoleList()
  },
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 10px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.addRoleBtn {
  margin-bottom: 20px;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>